/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador;

import Modelo.*;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author PeÑa
 */
@WebServlet(name = "ServletControlador", urlPatterns = {"/ServletControlador"})
public class ServletControlador extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            String accion = request.getParameter("accion");
            if (accion.equals("AnadirCarrito")) {
                this.AnadirCarrito(request, response);
                response.sendRedirect("MiCarrito.jsp");
            } else if (accion.equals("CancelarUno")) {
                this.CancelarUno(request, response);
                response.sendRedirect("MiCarrito.jsp");
            } else if (accion.equals("CancelarProducto")) {
                this.CancelarProducto(request, response);
                response.sendRedirect("MiCarrito.jsp");
            } else if (accion.equals("login")) {
                this.Login(request, response);
            } else if (accion.equals("logout")) {
                this.Logout(request, response);
            } else if (accion.equals("RegistrarPedido")) {
                this.RegistrarPedido(request, response);
            }else{
            response.sendRedirect("");
            }
        } catch (Exception ex) {
            response.sendRedirect("");
        }

    }

   
    private void RegistrarPedido(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Producto> carrito = (ArrayList<Producto>) session.getAttribute("carrito");
        Cliente Usuario = (Cliente) session.getAttribute("usuario");
        boolean rpta = false;
        if (carrito != null && Usuario != null) {
            rpta = PedidosBD.registrarPedido(carrito, Usuario);
        }
        if (rpta) {
            
            response.sendRedirect("Mensaje.jsp?mensaje=Pedido Registrado Con Exito, Espere Validacion del administrador");
        session.removeAttribute("carrito");
        } else {
            response.sendRedirect("Mensaje.jsp?mensaje=No se realizo Pedido");
        }
    }

    private void Logout(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("usuario");
        session.removeAttribute("carrito");
        response.sendRedirect("");
    }

    private void Login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cliente usuario;
        String password = request.getParameter("password");
        String user = request.getParameter("user");
        usuario = ClientesBD.login(user, password);
       
        if (usuario != null) {
            session.setAttribute("usuario", usuario);
            response.sendRedirect("index.jsp");
        } else {
            response.sendRedirect("index.jsp?mensaje=error al intentar iniciar session, verifique que sus datos sean correctos");
        }
    }

    private void CancelarUno(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Producto> carrito;
        Producto prod = new Producto();
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            carrito = (ArrayList<Producto>) session.getAttribute("carrito");
            prod = carrito.get(id);
            carrito.remove(id);
            prod.setCantidad(prod.getCantidad() - 1);
            if (prod.getCantidad() < 1) {
            } else {
                carrito.add(id, prod);
            }
            session.setAttribute("carrito", carrito);
        } catch (Exception e) {
        }

    }

    private void CancelarProducto(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Producto> carrito;

        try {
            int id = Integer.parseInt(request.getParameter("id"));
            carrito = (ArrayList<Producto>) session.getAttribute("carrito");
            carrito.remove(id);
            session.setAttribute("carrito", carrito);
        } catch (Exception e) {
        }
    }

    private void AnadirCarrito(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Producto> carrito = new ArrayList();
        Producto prod;
        boolean rep = false;
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            if (session.getAttribute("carrito") != null) {
                carrito = (ArrayList<Producto>) session.getAttribute("carrito");
                for (int i = 0; i < carrito.size(); i++) {
                    prod = carrito.get(i);
                    if (prod.getId() == id) {
                        prod.setCantidad(prod.getCantidad() + 1);
                        carrito.remove(i);
                        carrito.add(i, prod);
                        session.setAttribute("carrito", carrito);
                        rep = true;
                    }
                }
            }
            if (rep == false) {
                prod = ProductoBD.obtenerProducto(id);
                if (session.getAttribute("carrito") != null) {
                    carrito = (ArrayList<Producto>) session.getAttribute("carrito");
                    carrito.add(prod);
                    session.setAttribute("carrito", carrito);
                } else {
                    carrito.add(prod);
                    session.setAttribute("carrito", carrito);
                }

            }

        } catch (Exception ex) {

            response.sendRedirect("");
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
